﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace UpLoadApi.Controllers
{
    public class UploadController : ApiController
    {
        [HttpPost]
        public async Task<string> Post()
        {
            try
            {
                var task = this.Request.Content.ReadAsStreamAsync();

                task.Wait();

                string fileNameEncode = this.Request.Headers.GetValues("filename").FirstOrDefault<string>();

                //将BitConverter转换的string转换成byte[]
                string fileName = fileNameEncode;
                string[] strSplit = fileName.Split('-');
                byte[] bytTemp2 = new byte[strSplit.Length];
                for (int i = 0; i < strSplit.Length; i++)
                    bytTemp2[i] = byte.Parse(strSplit[i], System.Globalization.NumberStyles.AllowHexSpecifier);
                //将Byte重新用UTF8解码成真实文件名
                fileName = Encoding.UTF8.GetString(bytTemp2);


                Stream requestStream = task.Result;

                byte[] bytes = new byte[requestStream.Length];//requestStream.Length-10

                //设置当前流的位置为流开始的位置
                requestStream.Seek(0, SeekOrigin.Begin);//这个必须现在read之前进行定位 requestStream.Seek(10, SeekOrigin.Begin);
                requestStream.Read(bytes, 0, bytes.Length);//这里不能使用异步

                if (!Directory.Exists("E:/UpLoad/"))
                {
                    Directory.CreateDirectory("E:/UpLoad/");
                }
                

                //把bytes写入文件
                FileStream fs = new FileStream("E:/UpLoad/" + fileName, FileMode.Create);
                await fs.WriteAsync(bytes, 0, bytes.Length);

                fs.Close();
                fs.Dispose();
                requestStream.Close();
                requestStream.Dispose();
                
                return "Success";
            }
            catch (Exception ex)
            {
                return "Error "+ex.Message;
            }            
        }
        [HttpGet]
        public string Get()
        {
            return "Hello world!";
        }
    }
}
